package com.year.shiyi.service.impl;

import com.year.shiyi.common.utils.Result;
import com.year.shiyi.common.utils.oauth2.TokenGenerator;
import com.year.shiyi.entity.mybatis.SysUserTokenEntity;
import com.year.shiyi.mapper.SysUserTokenMapper;
import com.year.shiyi.service.SysUserTokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 系统用户Token 服务实现类
 * </p>
 *
 * @author shiyi
 * @since 2021-02-02
 */
@Service
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserTokenEntity> implements SysUserTokenService {

    /**
     * 过期时间
     */
    private final static int EXPIRED = 3600 * 12;

    @Override
    public Result<Object> createToken(long userId) {
        // 生成token
        String token = TokenGenerator.generateValue();

        // 当前时间
        Date now = new Date();
        // 过期时间
        Date expireTime = new Date(now.getTime() + EXPIRED * 1000);

        // 判断是否生成过token
        SysUserTokenEntity tokenEntity = this.getById(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            // 保存token
            this.save(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            // 更新token
            this.updateById(tokenEntity);
        }
        return Result.success(token);
    }

    @Override
    public Result<Object> logout(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        this.updateById(tokenEntity);
        return  null;
    }
}
